package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.admin.dict.service.DictItemService;
import com.fz.us.oa.core.entity.com.Certificate;
import com.fz.us.oa.core.service.com.CertificateService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/25.
 */
@Controller
@RequestMapping(value = "/com/certificate")
public class CertificateController extends BaseController {
    private static final long serialVersionUID = 1625630220108828559L;

    @Autowired
    private UserService userService;
    @Autowired
    private DictItemService dictItemService;
    @Autowired
    private CertificateService certificateService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> dictItems = getDictItems(user,"certName");
        if (StringUtils.isNotEmpty(keyId)){
            Certificate certificate=certificateService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("cert", certificate);
        }
        model.addAttribute("dictItems", dictItems);
        model.addAttribute("user", user);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/cert_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            Certificate certificate=certificateService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("stepNo", stepNo);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("cert", certificate);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/cert_read";
    }

    /**
     * 保存Model数据
     */
    private Certificate saveModel(User user, String keyId, String certType, String certDictItemId,
                                  String certNo, String userId, String datEvaluate, String datValid) throws ParseException {

        Certificate certificate = null;
        if (StringUtils.isBlank(keyId)) {
            certificate = new Certificate();
            certificate.setCreater(user);
            certificate.setCompany(user.getCompany());

            certificate.setName("资质名称");
        } else {
            certificate = certificateService.get(keyId);
        }

        certificate.setCertType(Integer.valueOf(certType));

        if (StringUtils.isNotBlank(certDictItemId)) {
            DictItem dictItem = dictItemService.get(certDictItemId);
            certificate.setCertDictItem(dictItem);
            certificate.setName(dictItem.getName());
        }

        if (StringUtils.isNotBlank(certNo)) {
            certificate.setCertNo(certNo);
        }

        if (StringUtils.isNotBlank(userId)) {
            certificate.setHandlerId(userId);
            User handler = userService.get(userId);
            certificate.setHandler(handler);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotBlank(datEvaluate)) {
            certificate.setDatEvaluate(sdf.parse(datEvaluate));
        }

        if (StringUtils.isNotBlank(datValid)) {
            certificate.setDatValid(sdf.parse(datValid));
        }

        if (certificate.getForm() == null) {
            certificate.setForm("公司资质登记表");
        }

        return certificate;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String certType, String certDictItemId,
                       String certNo, String userId, String datEvaluate, String datValid) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        Certificate certificate = saveModel(user,keyId,certType,certDictItemId,certNo,userId,datEvaluate,datValid);
        if(StringUtils.isNotEmpty(keyId)){
            certificateService.update(certificate);
            rMap.put("message", "更新成功");
        } else {
            certificateService.save(certificate, "com.fz.us.oa.core.entity.com.Certificate");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     *提交操作
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,
                         String certType, String certDictItemId,
                         String certNo, String userId, String datEvaluate, String datValid, String curDutyId, String comment) throws ParseException{

        Map<String,Object> rMap=new HashMap<String,Object>();
        Certificate certificate = saveModel(user,keyId,certType,certDictItemId,certNo,userId,datEvaluate,datValid);
        certificate.setNumStatus(1);
        certificate.setTxtStatus("使用中");

        if (StringUtils.isNotEmpty(keyId)) {
            certificateService.approve(certificate, dutyService.get(curDutyId), comment);
        } else {
            certificateService.commit(certificate, "com.fz.us.oa.core.entity.com.Certificate", dutyService.get(curDutyId));
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Certificate certificate=certificateService.get(keyId);
        certificateService.approve(certificate, dutyService.get(curDutyId), comment);

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Certificate certificate=certificateService.get(keyId);
            certificateService.back(certificate, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Certificate certificate=certificateService.get(keyId);
            certificateService.deny(certificate, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                    String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.desc);

        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //流转中
                params.put("numStatus", 1);
                searchResult = certificateService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Certificate", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished,FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},params);
            }else if(viewtype.equals("2")){
                //到期提醒
                params.put("numStatus", 2);
                searchResult = certificateService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Certificate", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("3")){
                //已失效
                params.put("numStatus", 3);
                searchResult = certificateService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Certificate", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }
        }else{
            //所有单子
            searchResult = certificateService.paging(null,null,order,
                    "com.fz.us.oa.core.entity.com.Certificate",
                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
        }

        List<Certificate> certificateList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Certificate certificate: certificateList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(certificate.getId())?"":certificate.getId());
            rMap.put("name", StringUtils.isEmpty(certificate.getName())?"":certificate.getName());

            if (certificate.getCertDictItem() != null) {
                DictItem dictItem = certificate.getCertDictItem();
                rMap.put("dictItemId", dictItem.getId());
                String definedName = dictItemService.getDefinedName(certificate.getCompany().getId(), dictItem.getId());
                rMap.put("dictItemName", StringUtils.isEmpty(definedName)?dictItem.getName():definedName);
            }

            if(certificate.getCertType()==1){
                rMap.put("certType", "企业证照");
            }else{
                rMap.put("certType", "企业资质");
            }

            rMap.put("certNo", certificate.getCertNo());
            rMap.put("datEvaluate", certificate.getDatEvaluate()==null ? "" : DataUtil.DateToString(certificate.getDatEvaluate()));
            rMap.put("datValid", certificate.getDatValid()==null ? "" : DataUtil.DateToString(certificate.getDatValid()));

            rMap.put("processStateName", certificate.getProcessState()==null?"": certificate.getProcessState().value());
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 弹出资质延续对话框
     */
    @RequestMapping(value = "continue/{keyId}", method = RequestMethod.GET)
    public String openDialog(@CurrentUser User user, Model model,
                             @PathVariable String keyId) {
        model.addAttribute("keyId", keyId);
        return "/com/cert_continue_dialog";
    }

    /**
     * 保存资质延续信息
     */
    @RequestMapping(value = "savecontinue/{keyId}", method = RequestMethod.POST)
    public Object saveDialogReturn(@CurrentUser User user,@PathVariable String keyId, String datEvaluate, String datValid) throws ParseException {
        Certificate certificate = certificateService.get(keyId);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotBlank(datEvaluate)) {
            certificate.setDatEvaluate(sdf.parse(datEvaluate));
        }

        if (StringUtils.isNotBlank(datValid)) {
            Date date = sdf.parse(datValid);
            certificate.setDatValid(date);

            Date datNow = new Date();
            if(DateUtils.truncatedCompareTo(date, datNow, Calendar.DATE)<0){
                certificate.setNumStatus(3);
                certificate.setTxtStatus("已失效");
            } else if(DateUtils.truncatedCompareTo(DateUtils.addDays(date,-30),datNow, Calendar.DATE)<0){
                certificate.setNumStatus(2);
                certificate.setTxtStatus("到期提醒");
            } else {
                certificate.setNumStatus(1);
                certificate.setTxtStatus("使用中");
            }
        }

        return ajaxJson(certificateService.saveEntity(certificate));
    }


}
